/**
 * 2022-10-12:restructuring with typescript, major alteration.
 */

const DEFAULT_COMPARE=(a:number|string,b:number|string):boolean=>{
    return a===b;
};

interface StateChangeHandle{
    (isEnter:boolean,changedStats:Array<string|number>):void
}

/**
 * state managment
 */
class State{

    private _state:Array<string|number>;
    private _changeCall:StateChangeHandle|null;

    constructor(...state:Array<string|number>) {
        this._state = [...state];
        this._changeCall=null;
    }

    /**
     * 状态改变时的回调
     */
    public set onChange(func:StateChangeHandle|null){
        this._changeCall=func;
    }

    /**
     * 获取状态序列
     */
    public get stats(){
        return this._state;
    }

    /**
     * 给定的值都存在时返回true
     */
    public exist(...stats:Array<string|number>):boolean{
        for(let st of stats){
            let index=this._state.findIndex((s)=>DEFAULT_COMPARE(s,st));
            if(index===-1)return false;
        }
        return true;
    }

    /**
     * 给定的值其中之一存在时返回true
     */
    public anyExist(...stats:Array<string|number>):boolean{
        for(let st of stats){
            let index=this._state.findIndex((s)=>DEFAULT_COMPARE(s,st));
            if(index!==-1)return true;
        }
        return false;
    }

    /**
     * 给定的值都不存在时返回true
     * @param stats
     * @returns {boolean}
     */
    public notExist(...stats:Array<string|number>):boolean{
        for(let st of stats){
            let index=this._state.findIndex((s)=>DEFAULT_COMPARE(s,st));
            if(index!==-1)return false;
        }
        return true;
    }

    /**
     * 给定的值其中之一不存在时返回true
     * @param stats
     * @returns {boolean}
     */
    public anyNotExist(...stats:Array<string|number>):boolean{
        for(let st of stats){
            let index=this._state.findIndex((s)=>DEFAULT_COMPARE(s,st));
            if(index===-1)return true;
        }
        return false;
    }

    /**
     * 添加状态值
     */
    public add(...stats:Array<string|number>):void{
        const changed=[];
        for(let st of stats){
            if(this._state.findIndex((s)=>DEFAULT_COMPARE(s,st))===-1){
                this._state.push(st);
                changed.push(st);
            }
        }
        if(this._changeCall)this._changeCall(true,changed);
    }

    /**
     * 移除状态值
     */
    public remove(...stats:Array<string|number>):void{
        const changed=[];
        for(let st of stats){
            let index=this._state.findIndex((s)=>DEFAULT_COMPARE(s,st));
            if(index===-1)continue;
            this._state.splice(index,1);
            changed.push(st);
        }
        if(this._changeCall)this._changeCall(false,changed);
    }

    /**
     * 清除状态值
     */
    public clear():void{
        const changed=[...this._state];
        this._state=[];
        if(this._changeCall)this._changeCall(false,changed);
    }
}

export {State};
export type {StateChangeHandle};